<template>
    <basic-container>
        <avue-crud v-bind="bindVal"
                   v-on="onEvent"
                   :page.sync="page"
                   v-model="form"
                   v-permission="{delBtn: 'SYSTEM_FILE_DELETE',editBtn: 'SYSTEM_FILE_UPDATE',viewBtn: 'SYSTEM_FILE_DETAIL'}"
                   :search.sync="searchFrom">

            <template slot="menuLeft" slot-scope="scope">
                <el-button type="success" v-permission="'SYSTEM_FILE_ADD'" icon="el-icon-upload" size="small"
                           @click.stop="isUpload=true">上传
                </el-button>
                <el-button type="danger" v-permission="'SYSTEM_FILE_DELETE'" icon="el-icon-delete" size="small"
                           @click.stop="deletes()">批量删除
                </el-button>
            </template>

            <template slot="menu" slot-scope="scope">
                <el-button type="text"
                           icon="el-icon-share"
                           @click="fileShareUrl(scope.row)"
                           size="small">复制外链
                </el-button>
            </template>

            <template slot="name" slot-scope="scope">
                <a target="_blank" class="el-link el-link--primary is-underline"
                   @click.stop="downloadFile(scope.row.mark)">
                    <span class="el-link--inner">{{ scope.row.name }}</span>
                </a>
            </template>

            <template slot="fileSize" slot-scope="scope">
                <el-tag>{{ scope.row.fileSize | bytesToSize }}</el-tag>
            </template>

            <template slot="storageType" slot-scope="scope">
                <el-tag>{{ scope.row.storageTypeStr }}</el-tag>
            </template>

            <template slot="createTime" slot-scope="scope">
                <el-tag>{{ scope.row.createTime }}</el-tag>
            </template>

            <template slot="storageType" slot-scope="scope">
                <el-tag>{{ scope.row.params.storageType }}</el-tag>
            </template>

            <template slot-scope="{disabled,size}" slot="fileTypeSearch">
                <el-input placeholder="请输入文件扩展名" :disabled="disabled" :size="size"
                          v-model="searchFrom.fileType_eq"></el-input>
            </template>

        </avue-crud>

        <el-dialog custom-class="update-file avue-dialog" v-dialogDrag :close-on-click-modal="false" append-to-body
                   :show-close="true" :close-on-press-escape="true" title="附件上传" center :visible.sync="isUpload"
                   :lock-scroll="false" width="412px">

            <el-row :span="24">
                <el-col :span="24">
                    文件存储位置：
                    <el-select v-model="fileStorageType" placeholder="请选择">
                        <el-option
                            v-for="item in fileStorageList"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code">
                        </el-option>
                    </el-select>
                </el-col>
            </el-row>

            <el-upload
                drag
                :action="update"
                :data="{storageType:fileStorageType}"
                :headers="uploadHeader"
                name="file" with-credentials :before-upload="uploadStar" :on-success="uploadSuccess"
                :on-error="uploadError">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
        </el-dialog>
    </basic-container>
</template>

<script>
import {downloadFile} from "@/util/util";
import store from "@/store";

export default window.$crudCommon({
    data() {
        return {
            searchFrom: {},
            update: window.urllist.upload,
            uploadHeader: {
                [window.$KEY.AUTH]: store.getters.tokenType + ' ' + store.getters.token
            },
            del: true,
            isUpload: false,
            fileStorageType: 'SERVER',
            fileStorageList: []
        }
    },
    created() {
        this.initDict();
    },
    filters: {
        bytesToSize(bytes) {
            if (bytes === 0) return '0 B';

            const k = 1024, sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],

                i = Math.floor(Math.log(bytes) / Math.log(k));

            return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
        }
    },
    methods: {
        initDict() {
            this.api['storageType']().then((res) => {
                this.fileStorageList = res.data.data;
            })
        },
        downloadFile(mark) {
            downloadFile(mark);
        },
        delBefore(callback) {
            this.$confirm(`删除文件后，所有调用文件处将无法下载，请谨慎操作, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                callback();
            })
        },
        uploadStar() {
            this.$NProgress.start();
        },
        uploadSuccess(response) {
            this.$NProgress.done();
            if (response.status) {
                this.isUpload = false;
                this.$message.success("上传成功");
                this.refreshChange();
            } else {
                this.$message.error(response.message);
            }
        },
        uploadError() {
            this.$NProgress.done();
            this.$message.error("文件上传失败，稍后重试");
        },
        fileShareUrl(data){
            this.api['getUrl'](data.mark).then(res=>{
                if (res.data.status){
                    this.$Clipboard({
                        text: res.data.data
                    }).then(() => {
                        this.$message.success('获取成功，已复制...')
                    }).catch(() => {
                        this.$message.error('获取失败')
                    });
                }
            })
        }
    }
}, {
    name: '/resource/file',
    data: 'list'
})
</script>

<style lang="scss" scoped>
.update-file {
    padding: 0px;
    text-align: center;
}
</style>